package com.yuanduan.mplus.view;


import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.cj.framework.app.BaseActivity;
import com.cj.framework.app.BaseApplication;
import com.cj.framework.util.FileUtils;
import com.cj.framework.util.HttpImp;
import com.cj.framework.util.IHttp;
import com.cj.framework.widget.CircleImageView;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.model.DBManager;
import com.yuanduan.mplus.model.entity.RS;
import com.yuanduan.mplus.model.entity.User;
import com.yuanduan.mplus.util.FileImageUpload;

import java.io.File;
import java.util.HashMap;

/**
 * 个人信息设置
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {
    private Toolbar toolbar;
    private ProgressDialog progressDialog;
    private CircleImageView ci_header;
    private TextView tv_name;
    private EditText et_phone;
    private TextView tv_sex;
    private TextView tv_age;
    private TextView tv_job;
    private ImageButton ib_ownerinsure;
    private TextView tv_ownerResult;
    private TextView tv_errorMessage;
    private RelativeLayout rl_insure;
    private RelativeLayout rl_name;
    private RelativeLayout rl_age;
    private RelativeLayout rl_sex;
    private RelativeLayout rl_job;
    private RelativeLayout rl_head;

    private static final int CAPTURE_IMAGE=110;
    private static final int GALLERY_IAMGE=111;
    private String name;
    private CharSequence sex;
    private String job;
    private Bitmap header;
    private Boolean isChangeHeader=false;
    private Boolean isChangeText=false;
    private User user;

    private IHttp iHttp=new HttpImp();
    private IHttp.HttpInfoCallbackWithIndex httpInfoCallback=new IHttp.HttpInfoCallbackWithIndex() {
        @Override
        public void onSucceed(Object result, int index) {
            progressDialog.dismiss();
            RS rs= (RS) Config.decry(result,RS.class);
            switch (index){
                case 0:
                    //更新到数据库
//                    updateFromDB();
//                    updateToView();
                    break;
                case 1://更改个人信息
                    if(rs.getRs()==1){
                        //更新数据库
                        user.setRealName(tv_name.getText().toString().trim());
                        user.setSex(tv_sex.getText().toString().trim().equals("男")?1:2);
                        user.setAge(tv_age.getText().toString().trim());
                        user.setProfessional(tv_job.getText().toString().trim());
                        DBManager.getInstance(getApplicationContext()).updateUser(user);
                        Intent intent=new Intent("com.cj.updateMainDB");
                        sendBroadcast(intent);
                        Toast.makeText(SettingActivity.this,"修改信息成功",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(SettingActivity.this,"修改失败",Toast.LENGTH_SHORT).show();
                    }

                    break;
            }
        }

        @Override
        public void onFailed(Object result, int index) {
            progressDialog.dismiss();
        }
    };

    @Override
    protected void findId() {
        rl_sex= (RelativeLayout) findViewById(R.id.setting_rl_sex);
        rl_job= (RelativeLayout) findViewById(R.id.setting_rl_job);
        rl_name= (RelativeLayout) findViewById(R.id.setting_rl_name);
        rl_age= (RelativeLayout) findViewById(R.id.setting_rl_age);
        rl_head= (RelativeLayout) findViewById(R.id.setting_rl_head);
        rl_insure= (RelativeLayout) findViewById(R.id.setting_rl_insure);
        toolbar= (Toolbar) findViewById(R.id.toolbar);
        ci_header = (CircleImageView) findViewById(R.id.personsetting_iv_head);
        tv_name = (TextView) findViewById(R.id.personsetting_et_name);
//        et_phone= (EditText) findViewById(R.id.personsetting_et_phone);
        tv_age = (TextView) findViewById(R.id.personsetting_et_age);
        tv_job = (TextView) findViewById(R.id.personsetting_et_job);
        tv_sex = (TextView) findViewById(R.id.personsetting_et_sex);
        ib_ownerinsure= (ImageButton) findViewById(R.id.personsetting_ib_owner);
        tv_ownerResult= (TextView) findViewById(R.id.personsetting_tv_owner);
        tv_errorMessage= (TextView) findViewById(R.id.personsetting_tv_errormessage);
    }

    @Override
    protected void logic() {
        et_phone.setEnabled(false);
        user=DBManager.getInstance(this).getUser();
        tv_name.setText(user.getRealName());
        et_phone.setText(user.getUserPhone());
        if(user.getSex()==0){
            tv_sex.setText("");
        }else if(user.getSex()==1){
            tv_sex.setText("男");
        }else {
            tv_sex.setText("女");
        }
        if(user.getAudit()==-1){
            tv_ownerResult.setText("未上传身份证扫描件");
        }else if(user.getAudit()==1){
            tv_ownerResult.setText("未审核");
        }else{
            tv_ownerResult.setText("已通过");
        }
        tv_age.setText(user.getAge());
        tv_job.setText(user.getProfessional());
//        age=user.getAge();
//        sex=user.getSex()==1?"男":"女";
//        name=user.getRealName();
//        job=user.getProfessional();
        header=FileUtils.getBitmapFromFile(Config.HEADLOCATION);
        if(header!=null){
            ci_header.setBitmap(FileUtils.getBitmapFromFile(Config.HEADLOCATION));
        }
        progressDialog=new ProgressDialog(this);
        //set toolbar;
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setTitle("个人设置");
        toolbar.setNavigationIcon(R.mipmap.back_arrow);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAll();
                SettingActivity.this.finish();
            }
        });

        rl_age.setOnClickListener(this);
        rl_job.setOnClickListener(this);
        rl_name.setOnClickListener(this);
        rl_sex.setOnClickListener(this);
        ci_header.setOnClickListener(this);
        ib_ownerinsure.setOnClickListener(this);
        rl_insure.setOnClickListener(this);
        rl_head.setOnClickListener(this);

//        updateFromDB();
//        updateToView();
//        updateFromInternet();
    }


    private void saveToInternet(){
        if(isChangeHeader||isChangeText){
//            progressDialog.show();
        }

        if(isChangeText){
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("UserPhone",user.getUserPhone());
            hashMap.put("UserPassword",user.getUserPwd());
            hashMap.put("RealName",name);
            Log.d("xx","sex to string::"+sex.toString());
            String tt=sex.equals("男")?"1":"2";
            hashMap.put("Sex",sex.equals("男")?"1":"2");
            hashMap.put("Professional",job);
            iHttp.httpInfoPostWithIndex(Config.URL+Config.MODIFYUSERINFO, Config.translateMap(hashMap), httpInfoCallback, 1);
        }
    }

    private void checkAll() {
        if(!isChangeText){

        }else {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("UserPhone", user.getUserPhone());
            hashMap.put("UserPassword", user.getUserPwd());
            hashMap.put("RealName", tv_name.getText().toString().trim());
            hashMap.put("Sex", tv_sex.getText().toString().trim().equals("男") ? "1" : "2");
            hashMap.put("Professional", tv_job.getText().toString().trim());
            iHttp.httpInfoPostWithIndex(Config.URL + Config.MODIFYUSERINFO, Config.translateMap(hashMap), httpInfoCallback, 1);
        }
        if(isChangeHeader) {
            if(TextUtils.isEmpty(mFilePath)){
                return;
            }
            new Thread(){
                @Override
                public void run() {
                    HashMap<String,String> hashMap=new HashMap<String, String>();
                    hashMap.put("UserPhone",user.getUserPhone());
                    hashMap.put("UserPassword",user.getUserPwd());
//                    String result=FileImageUpload.uploadFile(new File(mFilePath),"Head",Config.translateMap(hashMap),Config.URL+Config.MODIFYUSERHEAD);
                    FileUtils.saveBitmap(Config.HEADLOCATION,header);
                    Intent intent=new Intent("com.cj.updateMainImg");
                    sendBroadcast(intent);
                }
            }.start();
        }
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_setting;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
//            case R.id.menu_save:
////                saveToInternet();
//                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void updateFromInternet(){
        //从网络更新数据到数据库
        iHttp.httpInfoPostWithIndex(Config.URL,new HashMap<String, String>(),httpInfoCallback,0);
    }


    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.personsetting_iv_head:
                //选取照片并更新字段和更新view
                break;
            case R.id.personsetting_ib_owner:
                openActivity(OwnerInsureActivity.class);
                break;
            case R.id.setting_rl_insure:
                openActivity(OwnerInsureActivity.class);
                break;
            case R.id.setting_rl_age:
//                new MaterialDialog.Builder(this)
//                        .title("输入年龄")
//                        .inputType(InputType.TYPE_CLASS_NUMBER)
//                        .input("年龄", "", false, new MaterialDialog.InputCallback() {
//                            @Override
//                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
//                                isChangeText=true;
//                                age=input.toString();
//                                tv_age.setText(input);
//                            }
//                        }).show();
                break;
            case R.id.setting_rl_head:
                new MaterialDialog.Builder(this)
                        .title("设置头像")
                        .items(R.array.pickHead)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                isChangeHeader=true;
                                switch(which){
                                    case 0:
                                        capture();
                                        break;
                                    case 1:
                                        selectImage();
                                        break;
                                }
                            }
                        })
                        .show();
                break;
            case R.id.setting_rl_job:
                new MaterialDialog.Builder(this)
                        .title("选择职业")
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .input("职业", "", false, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                isChangeText=true;
                                tv_job.setText(input);
                                job=input.toString();
                            }
                        }).show();
//                new MaterialDialog.Builder(this)
//                        .title("选择职业")
//                        .items(R.array.job)
//                        .itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
//                            @Override
//                            public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
//                                isChangeText=true;
//                                tv_job.setText(text);
//                                job= text.toString();
//                                return false;
//                            }
//                        })
//                        .positiveText("确定")
//                        .show();
                break;
            case R.id.setting_rl_sex:
                new MaterialDialog.Builder(this)
                        .title("选择性别")
                        .items(R.array.sex)
                        .itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                isChangeText=true;
                                sex=text.toString();
                                tv_sex.setText(text);
                                return false;
                            }
                        })
                        .positiveText("确定")
                        .show();
                break;
            case R.id.setting_rl_name:
                new MaterialDialog.Builder(this)
                        .title("输入名字")
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .input("姓名", "", false, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                isChangeText=true;
                                name=input.toString();
                                tv_name.setText(input);
                            }
                        }).show();
                break;
        }
    }

    private void selectImage() {
        Intent intent=new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        if(intent.resolveActivity(getPackageManager())!=null){
            startActivityForResult(intent,GALLERY_IAMGE);
        }
    }

    private void capture(){
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getPackageManager())!=null){
            File file=createFile();
            if(file!=null){
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent,CAPTURE_IMAGE);
            }
        }else{
            Toast.makeText(this,"无法启动相机",Toast.LENGTH_SHORT).show();
        }
    }

    private String mCurrentPath;
    private File createFile() {
        File file=new File(getExternalCacheDir(),"head.jpeg");
        mCurrentPath=file.getAbsolutePath();
        return file;
    }
    private String mFilePath;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==RESULT_OK){
            String filePath=null;
            if(requestCode==CAPTURE_IMAGE){
                if(mCurrentPath!=null){
                    filePath=mCurrentPath;
                }
            }else if(requestCode==GALLERY_IAMGE){
                filePath=getPath(data.getData());
            }
            if(!TextUtils.isEmpty(filePath)){
                mFilePath=filePath;
                header= BitmapFactory.decodeFile(filePath);
                ci_header.setBitmap(header);
            }
        }
    }

    private String getPath(Uri data) {
        String filePath=null;
        String[] ff=new String[]{MediaStore.MediaColumns.DATA};
        Cursor cursor=getContentResolver().query(data,ff,null,null,null);
        if(cursor==null){
            return null;
        }
        cursor.moveToFirst();
        filePath=cursor.getString(cursor.getColumnIndex(ff[0]));
        cursor.close();
        return filePath;
    }

}
